package com.rico.kok.controller.user;

import com.rico.kok.config.FileDirConfig;
import com.rico.kok.entity.User;
import com.rico.kok.service.UserServiceImpl;
import com.rico.kok.service.interf.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@Controller
public class LoginController {

    @Autowired
    UserService userService;

    @Autowired
    FileDirConfig fileDirConfig;

    @RequestMapping("/login.html")
    public String toLogin(){
        return "login";
    }

    /**
     *
     * @param principle     用户名
     * @param credentials   密码
     * @param url           登陆后需要回到的页面
     * @param request
     * @param response
     * @param model
     * @return
     */
    @PostMapping("/login.htm")
    public String login(@RequestParam("username") String principle, @RequestParam("password") String credentials,@RequestParam(value = "recentUrl",defaultValue = "/") String url, HttpServletRequest request, HttpServletResponse response, Model model) {
        UsernamePasswordToken token = new UsernamePasswordToken(principle, credentials);
        try {
            //认证token
            SecurityUtils.getSubject().login(token);
            //设置认证有效时间
            SecurityUtils.getSubject().getSession().setTimeout(60*300);
            //获取认证用户
            List<User> users = userService.selectUsers(new User(principle));
            User user=users.get(0);
            //将用户放入session中
            request.getSession().setAttribute("user",user);
            //设置session过期时间
            request.getSession().setMaxInactiveInterval(60*300);


            //跳转到iframe的父页面
            PrintWriter out = response.getWriter();
            if ("/".equals(url)){
                out.print("<script>window.parent.location.href='/';</script>");
            }else {
                out.print("<script>window.location.href='"+url+"';</script>");
            }
            out.flush();

        } catch (UnknownAccountException e) {
            //用户名错误
            model.addAttribute("code", "error");
            model.addAttribute("msg", "用户名不存在！");
            return "msg";
        } catch (IncorrectCredentialsException e) {
            //密码错误
            model.addAttribute("code", "error");
            model.addAttribute("msg", "密码不正确！");
            return "msg";
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @RequestMapping("/logout.htm")
    public String logout(HttpSession session) {
        session.setAttribute("user",null);
        SecurityUtils.getSubject().logout();
        return "redirect:/";
    }
}
